<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getDayRunRateList"
    :columns="columns"
    :onFromReset="onFromReset"
    :onValuesChange="onChange"
    searchText="统计"
  >
    <template #toolbars>
      <div class="w-full flex justify-between mr-4">
        <Space :size="20">
          <div
            :class="['report_item', { active: currentValue == null }]"
            @click="onSearch(null)"
          >
            <div>
              <span>全部设备</span>
            </div>
            <div>
              <span>设备数</span>
              <span class="num">{{ deviceCount['0'] || 0 }}</span>
            </div>
          </div>
          <div
            :class="['report_item', { active: currentValue == 1 }]"
            @click="onSearch(1)"
          >
            <div>
              <span>平均运行率</span>
              <span>95%以上</span>
            </div>
            <div>
              <span>设备数</span>
              <span class="num">{{ deviceCount[1] || 0 }}</span>
            </div>
          </div>
          <div
            :class="['report_item', { active: currentValue == 2 }]"
            @click="onSearch(2)"
          >
            <div>
              <span>平均运行率</span>
              <span>95%~90%</span>
            </div>
            <div>
              <span>设备数</span>
              <span class="num">{{ deviceCount[2] || 0 }}</span>
            </div>
          </div>
          <div
            :class="['report_item', { active: currentValue == 3 }]"
            @click="onSearch(3)"
          >
            <div>
              <span>平均运行率</span>
              <span>90%以下</span>
            </div>
            <div>
              <span>设备数</span>
              <span class="num">{{ deviceCount[3] || 0 }}</span>
            </div>
          </div>
        </Space>
        <Space>
          <b-button icon="export" @click="onExport" code="weeklyReport:export"
            >导出</b-button
          >
        </Space>
      </div>
    </template>
  </ProTable>
</template>

<script lang="tsx" setup>
import { computed, ref } from 'vue';
import { Descriptions, DescriptionsItem, Space } from 'ant-design-vue';
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { isEmptyObject, listToEnum } from '@/utils/utils';
import { getModelInfoById } from '@/api/push';
import { exportDayList, getDayRunRateList } from '@/api/statistics';
import CustomRange from '../components/customRange.vue';
import CustomTree from '../components/customTree.vue';
import { reportStore } from '../store';

dayjs.extend(isoWeek);
const modListEnum = ref<Record<string, any>>({});
const onChange = async (params: any, formState: any) => {
  if (params.hasOwnProperty('deviceType')) {
    formState.modelId = undefined;
    if (params.deviceType) {
      const res = await getModelInfoById({
        type: params.deviceType,
        modelIds: '',
      });
      modListEnum.value = listToEnum(res.data, 'modelId', 'model');
    } else {
      modListEnum.value = {};
    }
  }
};

const {
  refreshStore,
  deviceModeOptions,
  deviceModeEnum,
  getModelOptions,
  getModelEnum,
  projectList,
} = reportStore();

const init = () => {
  refreshStore.timeDelay();
};

init();
const recordParams = ref({});
const deviceCount = ref({});
const _getDayRunRateList = async (queryParams: any) => {
  if (queryParams.hasOwnProperty('time')) {
    queryParams['startTime'] = getWeekFirstDay(queryParams.time[0]);
    (queryParams['endTime'] = getWeekLastDay(queryParams.time[1])),
      // queryParams.time = [
      //   getWeekFirstDay(queryParams.time[0]),
      //   getWeekLastDay(queryParams.time[1]),
      // ];
      getDateRange(queryParams['time']);
  }
  queryParams.type = 2;
  queryParams.runRate = currentValue.value;
  recordParams.value = queryParams;
  const res: any = await getDayRunRateList(queryParams);
  if (res.code !== 200) return;
  const { count, list } = res.data;
  deviceCount.value = count;
  const { pageNum, pageSize } = queryParams;
  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const newList = list.slice(startIndex, endIndex);
  const rows = newList.map((item: any) => {
    const obj: any = {};
    item.dateList.forEach((i: any) => {
      for (const [key, value] of Object.entries(i)) {
        obj[key] = value;
      }
    });
    return {
      ...obj,
      ...item,
    };
  });
  return {
    rows,
    total: list.length,
  };
};
const tableRef = ref();
const currentValue = ref(null);
const onSearch = (runRate: any) => {
  if (currentValue.value === runRate) {
    tableRef.value.search({ runRate: null });
    currentValue.value = null;
    return;
  }
  tableRef.value.search({ runRate });
  currentValue.value = runRate;
};

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '设备序列号',
    dataIndex: 'code',
    hideInSearch: true,
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    hideInSearch: true,
  },
  {
    title: '项目名称',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(formState) {
      const onChangeForTree = (value: any) => {
        formState['projectId'] = value;
      };
      return (
        <CustomTree
          filed='projectId'
          formState={formState}
          data={projectList.value}
          onChange={onChangeForTree}
        ></CustomTree>
      );
    },
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: {
      ...deviceModeEnum.value,
    },
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    hideInTable: true,
    valueEnum: isEmptyObject(modListEnum.value)
      ? {
          ...getModelEnum.value,
        }
      : { ...modListEnum.value },
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    width: 150,
    hideInSearch: true,
    valueEnum: {
      ...getModelEnum.value,
    },
  },
  {
    title: '运行日期',
    dataIndex: 'time',
    hideInTable: true,
    defaultValue: getPreviousSevenDays(),
    customSearchRender(formState) {
      const onChangeForTree = (value: any) => {
        formState['time'] = value;
      };
      return (
        <CustomRange
          formState={formState}
          picker='week'
          type='week'
          maxDay={77}
          defaultValue={getPreviousSevenDays()}
          onChange={onChangeForTree}
        ></CustomRange>
      );
    },
  },
  {
    title: '安装单位',
    dataIndex: 'address',
    hideInSearch: true,
  },
  ...dateColumns.value,
  {
    title: '平均运行率',
    dataIndex: 'runRate',
    hideInSearch: true,
    width: 120,
    customRender({ text }) {
      return <span>{text + '%'}</span>;
    },
  },
]);
const dateColumns: any = ref([]);

// 获取默认前三周日期
const getPreviousSevenDays = () => {
  const today = new Date();
  const todayDayOfWeek = today.getDay();

  let previousMonday;
  if (todayDayOfWeek === 0) {
    previousMonday = new Date(today);
    previousMonday.setDate(today.getDate() - 7);
  } else {
    previousMonday = new Date(today);
    previousMonday.setDate(today.getDate() - todayDayOfWeek + 1);
  }

  let firstWeekMonday = new Date(previousMonday);
  firstWeekMonday.setDate(previousMonday.getDate() - 21);
  let thirdWeekSunday = new Date(firstWeekMonday);
  thirdWeekSunday.setDate(firstWeekMonday.getDate() + 14 + 6);

  const formatDate = (date: any) => date.toISOString().split('T')[0];
  return [formatDate(firstWeekMonday), formatDate(thirdWeekSunday)];
};

// 根据选中时间生成列
const getDateRange = (date: any) => {
  const [start, end] = date;
  const startDate = new Date(start);
  const endDate = new Date(end);
  console.log(dayjs(endDate).format('YYYY-MM-DD'), '1');

  const weeks = [];
  let currentDate = new Date(startDate);
  while (currentDate < endDate) {
    const day = dayjs(currentDate).format('YYYY-MM-DD');
    const week = getWeekOfYear(day);
    weeks.push(week);
    currentDate.setDate(currentDate.getDate() + 7);
  }
  dateColumns.value = weeks.map((item: any) => {
    return {
      title: item,
      dataIndex: item,
      hideInSearch: true,
      width: 120,
      customRender({ text }) {
        return <span>{text + '%'}</span>;
      },
    };
  });
};

// 获取几几年第几周
const getWeekOfYear = (date: any) => {
  console.log(date, 'date');

  const day = dayjs(date);
  const weekNumber = day.isoWeek();
  const year = day.isoWeekYear();
  return `${year}第${weekNumber}周`;
};

// 获取当前周第一天
const getWeekFirstDay = (dateString: any) => {
  const date = new Date(dateString);
  const dayOfWeek = date.getDay();

  const firstDayOfWeek = new Date(date);
  firstDayOfWeek.setDate(
    date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1),
  );
  const firstDayString = firstDayOfWeek.toISOString().split('T')[0];
  return firstDayString;
};

// 获取当前周最后一天
const getWeekLastDay = (dateString: any) => {
  const date = new Date(dateString);
  const dayOfWeek = date.getDay();
  const lastDayOfWeek = new Date(date);
  lastDayOfWeek.setDate(date.getDate() + (dayOfWeek ? dayOfWeek : 7 - 7));
  const lastDayString = lastDayOfWeek.toISOString().split('T')[0];
  return lastDayString;
};

// 导出
const onExport = async () => {
  await exportDayList(recordParams.value);
};

const onFromReset = (params: any) => {
  currentValue.value = null;
  tableRef.value.search();
};
</script>
